<template>
    <div class="main">
        <div class="air-column">
            <h2>乘机人</h2>
            <el-form class="member-info" :model="form">
                <el-form-item prop="users">
                    <div>
                        <div class="member-info-item" v-for="(item, index) in form.users" :key="index">

                            <el-form-item label="乘机人">
                                <!-- 需要进行双向数据绑定 -->
                                <el-input placeholder="姓名" class="input-with-select" v-model="item.username">
                                </el-input>
                            </el-form-item>

                            <el-form-item label="证件类型">
                                <el-input placeholder="证件号码" class="input-with-select" v-model="item.id">
                                    <el-select slot="prepend" :value="item.idType" v-model="item.idType" placeholder="请选择">
                                        <el-option label="身份证" :value="1" :checked="true"></el-option>
                                        <el-option label="护照" :value="2"></el-option>
                                    </el-select>
                                </el-input>
                            </el-form-item>

                            <span class="delete-user" @click="handleDeleteUser(index)">-</span>
                        </div>
                    </div>
                </el-form-item>
            </el-form>


            <el-button class="add-member" type='primary' @click="handleAddUsers">添加乘机人</el-button>
        </div>

        <div class="air-column">
            <h2>保险</h2>
            <div>
                <div class="insurance-item" v-for="(item, index) in infoData.insurances" :key="index">
                    <el-checkbox @change="handleInsurance(item)"
                        :label="`${item.type}：￥${item.price}/份 × ${form.users.length}  最高赔付${item.compensation}`" border>
                    </el-checkbox>
                </div>
            </div>
        </div>
        <input type="hidden" :value="allPrice">
        <div class="air-column">
            <h2>联系人</h2>
            <div class="contact">
                <el-form label-width="80px" :model="form" :rules="rules" ref="form">
                    <el-form-item label="姓名" prop="contactName">
                        <el-input v-model="form.contactName"></el-input>
                    </el-form-item>

                    <el-form-item label="手机" prop="contactPhone">
                        <el-input placeholder="请输入内容" v-model="form.contactPhone">
                            <template slot="append">
                                <el-button @click="handleSendCaptcha">发送验证码</el-button>
                            </template>
                        </el-input>
                    </el-form-item>

                    <el-form-item label="验证码" prop="captcha">
                        <el-input v-model="form.captcha"></el-input>
                    </el-form-item>
                </el-form>
                <el-button type="warning" class="submit" @click="handleSubmit">提交订单</el-button>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    computed: {
        // 计算总价格
        allPrice() {
            let price = 0;
            let len = this.form.users.length;

            price += this.data.seat_infos.org_settle_price * len;
            let temp = 0//保险总价
            this.insurancesduixiang.forEach(v => {
                price += v.price * len;
                temp += v.price
            });
            console.log(temp)
            this.$emit("setbaoxianprice", temp)
            //方案2：
            // for(let i=0;i<this.form.insurances.length;i++){
            //     price+=this.form.insurances[i].price
            //     console.log(i,price)
            // }

            price += this.data.airport_tax_audlet * len;
            // 触发设置总金额事件
            this.$emit("setAllPrice", price)
            console.log('12312', price)
            return price;
        },
    },
    props: {
        // 接收机票信息
        data: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            infoData: {},
            rules: {
                contactName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
                contactPhone: [
                    { required: true, message: '请输入手机号码' },
                    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确' }
                ],
                captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
            },
            infoData: {},
            insurancesduixiang: [],
            form: {
                // 乘机人的列表
                users: [
                    {
                        username: "",
                        id: "",
                        idType: 1
                    }
                ],
                insurances: [],
                contactName: "",
                contactPhone: "",
                captcha: "", // 文档中缺少该属性（文档中写错了）
                invoice: true,
                seat_xid: this.$route.query.seat_xid,
                air: this.$route.query.id,
            },

        }
    },
    mounted() {
        this.$emit("setcountpeople", this.form.users.length)
        // 请求机票详细信息（保险还有右侧栏需要的数据）
        const { id, seat_xid } = this.$route.query;
        console.log(999, id, seat_xid)
        this.$axios({
            url: "/airs/" + id,
            params: {
                seat_xid
            }
        }).then(res => {
            // 赋值给机票的详细信息
            this.infoData = res.data;
            // 把infoData保存到store
            this.$store.commit("air/setOrderDetail", this.infoData)
        })
    },
    methods: {
        // 选择保险
        handleInsurance(id) {
            const index = this.form.insurances.indexOf(id.id);
            // 存在则去除
            if (this.insurancesduixiang.indexOf(id) > -1) {
                let arr = this.insurancesduixiang.slice(0);
                arr.splice(this.insurancesduixiang.indexOf(id), 1);
                //console.log(arr)
                this.insurancesduixiang = arr;

                this.form.insurances.splice(index, 1);
            } else { // 不存在添加到insurances
                this.insurancesduixiang = [...new Set([...this.insurancesduixiang, id])]
                //console.log('aaa',this.form.insurances)

                this.form.insurances.push(id.id);
            }

            console.log('aa:', this.form.insurances)
            console.log('bb:', this.insurancesduixiang)
        },
        // 添加乘机人
        handleAddUsers() {
            this.form.users.push(
                {
                    username: "",
                    id: "",
                    idType: 1
                }
            );
            console.log(this.form.users)
            this.$emit("setcountpeople", this.form.users.length)//回传如order，然后order传侧边栏
        },

        // 移除乘机人
        handleDeleteUser(index) {
            this.form.users.splice(index, 1);
            this.$emit("setcountpeople", this.form.users.length)
        },

        // 发送手机验证码
        handleSendCaptcha() {
            if (!this.form.contactPhone) {
                this.$confirm('手机号码不能为空', '提示', {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                    type: 'warning'
                })
                return;
            }

            if (this.form.contactPhone.length !== 11) {
                this.$confirm('手机号码格式错误', '提示', {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                    type: 'warning'
                })
                return;
            }

            this.$axios({
                url: `/captchas`,
                method: "POST",
                data: {
                    tel: this.form.contactPhone
                }
            }).then(res => {
                const { code } = res.data;
                this.$confirm(`模拟手机验证码为：${code}`, '提示', {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                    type: 'warning'
                })
            })
        },

        // 提交订单
        handleSubmit() {
            let valid=0;
            console.log(this.form.users.length)
            for(let i=0;i< this.form.users.length;i++){
                if(this.form.users[i].id==''||this.form.users[i].id.length!=18){
                    valid=1
                }
            }
            if(valid){
                this.$confirm("身份证id有问题", '提示', {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                    type: 'warning'
                })
                return
            }
            console.log('before:', this.form.insurances)
            this.$axios({
                url: `/airorders`,
                method: "POST",
                data: this.form,
                headers: {
                    Authorization: `Bearer ` + this.$store.state.user.userInfo.token
                }
            }).then(res => {
                this.$message.success("订单提交成功");
                //跳转到付款页
                setTimeout(() => {
                    this.$router.push({
                        path: "/air/pay",
                        query: {
                            amount: res.data.data.price,
                            orderNo: res.data.data.orderNo, // 订单id
                            id: res.data.data.id
                        }
                    })
                }, 1500);
            }).catch(err => {
                const { message } = err.response.data;
                // 警告提示
                this.$confirm(message, '提示', {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                    type: 'warning'
                })
            })
        }
    }
}
</script>

<style scoped lang="less">
.air-column {
    border-bottom: 1px #ddd dashed;
    padding-bottom: 20px;
    margin-bottom: 20px;
}

.air-column h2 {
    margin-bottom: 20px;
    font-size: 22px;
    font-weight: normal;
}

/deep/ .el-select .el-input {
    width: 130px;
}

.input-with-select {
    width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
    background-color: #fff;
}

.member-info /deep/ .el-form-item {
    margin-bottom: 0;
}

.member-info-item {
    border-bottom: 1px #eee dashed;
    padding-bottom: 20px;
    position: relative;

    &:first-child {
        .delete-user {
            display: none;
        }
    }
}

.add-member {
    margin-top: 20px;
}

.delete-user {
    display: block;
    background: #ddd;
    width: 16px;
    height: 16px;
    font-size: 14px;
    text-align: center;
    line-height: 16px;
    color: #fff;
    cursor: pointer;
    border-radius: 50px;
    position: absolute;
    right: -30px;
    top: 50%;
}

.insurance {
    >div {
        margin-top: 10px;
    }
}

.insurance-item {
    margin-bottom: 20px;
}

.contact {
    /deep/ .el-input {
        width: 50%;
    }
}

.submit {
    margin: 50px auto;
    display: block;
    width: 250px;
    height: 50px;
}
</style>